package rebot

import (
	"fmt"
	"github.com/eatmoreapple/openwechat"
	"goocr/data_treating"
	"goocr/img_ocr"
	"goocr/util"
	"io"
	"os/exec"
	"runtime"
)

func LoginWechat(robotName string) *openwechat.Bot {
	bot := openwechat.DefaultBot(openwechat.Desktop)
	bot.UUIDCallback = generateQrCodeCallback

	reloadStorage := openwechat.NewFileHotReloadStorage(fmt.Sprint(robotName, ".json"))
	defer func(reloadStorage io.ReadWriteCloser) {
		_ = reloadStorage.Close()
	}(reloadStorage)

	// 执行热登录
	if err := bot.HotLogin(reloadStorage, openwechat.NewRetryLoginOption()); err != nil {
		util.LogError(fmt.Sprintf("登录失败: %v", err))
		return nil
	}

	return bot
}
func generateQrCodeCallback(uuid string) {
	qrcodeUrl := openwechat.GetQrcodeUrl(uuid)
	util.LogInfo(fmt.Sprintf("登录地址:%s", qrcodeUrl))
	util.SaveCodeImg(qrcodeUrl)
}

func openURL(url string) error {
	var cmd string
	var args []string

	switch runtime.GOOS {
	case "windows":
		cmd = "cmd"
		args = []string{"/c", "start", url}
	default:
		return fmt.Errorf("unsupported platform")
	}

	return exec.Command(cmd, args...).Start()
}

func WechatRobot(bot *openwechat.Bot) {
	bot.MessageHandler = func(msg *openwechat.Message) {
		if !msg.IsSendByGroup() {
			return
		}
		if !msg.IsPicture() {
			return
		}
		filePath := data_treating.GetFilePath()
		if err := msg.SaveFileToLocal(filePath); err != nil {
			util.LogError(fmt.Sprintf("另存文件出错:%v", err))
			return
		}
		// 检查给定图像文件是否包含二维码
		isErcode, err := img_ocr.IsQRCode(filePath)
		if err != nil {
			util.LogError(fmt.Sprintf("检查给定图像文件是否包含二维码出错:%v", err))
			return
		}
		if isErcode {
			//删除二维码图片
			util.LogInfo(fmt.Sprintf("删除二维码图片%s结果:%v", filePath, data_treating.RemoveFile(filePath)))
			return
		}
		util.LogInfo("另存文件成功")
	}

}
